package com.sqx.modules.orders.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.Constant.OrdersConstants;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.service.*;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.course.dao.CourseDao;
import com.sqx.modules.course.dao.CourseDetailsDao;
import com.sqx.modules.course.dao.CourseUserDao;
import com.sqx.modules.course.entity.Course;
import com.sqx.modules.course.entity.CourseDetails;
import com.sqx.modules.course.entity.CourseUser;
import com.sqx.modules.course.service.CourseDetailsService;
import com.sqx.modules.course.service.CourseUserService;
import com.sqx.modules.invite.dao.InviteMoneyDao;
import com.sqx.modules.invite.entity.InviteMoney;
import com.sqx.modules.invite.service.InviteService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.orders.entity.dto.DramaPointPayDto;
import com.sqx.modules.orders.entity.vo.OrdesVo;
import com.sqx.modules.orders.entity.vo.ProductVo;
import com.sqx.modules.orders.service.OrdersService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayClassifyDao;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.dao.UserDramaDetailsDao;
import com.sqx.modules.pay.dao.UserDramaPointDao;
import com.sqx.modules.pay.entity.PayClassify;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.entity.UserDramaDetails;
import com.sqx.modules.pay.entity.UserDramaPoint;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.utils.AliPayOrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private WxService wxService;
    @Autowired
    private AliPayController aliPayController;
    @Autowired
    private CourseDao courseDao;
    @Autowired
    private CourseUserDao courseUserDao;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private CourseUserService courseUserService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private VipDetailsService vipDetailsService;
    @Autowired
    private CourseDetailsService courseDetailsService;
    @Autowired
    private UserMoneyService userMoneyService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private UserService userService;
    @Autowired
    private InviteService inviteService;
    @Autowired
    private InviteMoneyDao inviteMoneyDao;
    @Autowired
    private PayClassifyDao payClassifyDao;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private UserDramaDetailsDao userDramaDetailsDao;
    @Autowired
    private UserDramaPointDao userDramaPointDao;
    @Autowired
    private CourseDetailsDao courseDetailsDao;
    @Autowired
    private OrdersDao ordersDao;


    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);


    @Override
    public Orders selectOrdersByCourseIdAndUserId(Long userId, Long courseId) {
        return baseMapper.selectOrdersByCourseIdAndUserId(userId, courseId);
    }

    /**
     * 订单的种类是短剧，将短剧加入到我的列表，
     * 订单的种类是会员，将会员到期时间更新：如果用户没有成为过会员，则直接更新到期时间，如果用户成为过会员，则将到期时间延长
     * @param orders
     */
    @Override
    @Transactional
    public Result insertOrders(Orders orders) {
        //如果订单的种类是短剧
        if (orders.getOrdersType() == 1) {
            //将短剧加入到我的列表
            CourseUser courseUser = new CourseUser();
            //设置短剧id
            courseUser.setCourseId(orders.getCourseId());
            courseUser.setCourseDetailsId(orders.getCourseDetailsId());
            if (courseUser.getCourseDetailsId() != null) {
                courseUser.setClassify(2);
            } else {
                courseUser.setClassify(1);
            }
            //设置用户id
            courseUser.setUserId(orders.getUserId());
            //设置订单id
            courseUser.setOrderId(orders.getOrdersId());
            //加入我的列表
            courseUserService.insertCourseUser(courseUser);
            //todo 购买次数加一
//            LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            courseLambdaQueryWrapper.eq(Course::getCourseId, orders.getCourseId());
//            Course course = courseDao.selectOne(courseLambdaQueryWrapper);
//            course.setPayNum(course.getPayNum() + 1);
//            courseDao.updateById(course);
            return Result.success("短剧订单处理完成！");
        } else if (orders.getOrdersType() == 2){
            //订单的种类是会员
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //查询用户是否成为过会员
            UserVip userVip = userVipService.selectUserVipByUserId(orders.getUserId());
            if (userVip != null) {
                //日历
                Calendar cal = Calendar.getInstance();

                //会员没有到期
                if (userVip.getIsVip().equals(2)) {
                    try {
                        orders.setExpired(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(userVip.getEndTime()));
                        ordersDao.updateById(orders);
                        //将会员到期时间设置在日历表中
                        cal.setTime(sdf.parse(userVip.getEndTime()));
                        //判断续费会员的时间
                        if (orders.getVipNameType() == 0) {
                            //一个月
                            cal.add(Calendar.MONTH, 1);
                        } else if (orders.getVipNameType() == 1) {
                            //一季度
                            cal.add(Calendar.MONTH, 3);
                        } else if (orders.getVipNameType() == 2) {
                            //一年
                            cal.add(Calendar.YEAR, 1);
                        }
                        userVip.setIsVip(2);
                        //更新会员的开通时间
                        userVip.setCreateTime(sdf.format(new Date()));
                        //更新会员的到期时间
                        userVip.setEndTime(sdf.format(cal.getTime()));
                        //更新会员信息
                        userVipService.updateById(userVip);
                        return Result.success().put("data", "未到期会员续费成功！");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    //会员到期了
                    //将现在的时间设置在日历中
                    cal.setTime(new Date());
                    //判断续费会员的时间
                    if (orders.getVipNameType() == 0) {
                        //一个月
                        cal.add(Calendar.MONTH, 1);
                    } else if (orders.getVipNameType() == 1) {
                        //一季度
                        cal.add(Calendar.MONTH, 3);
                    } else if (orders.getVipNameType() == 2) {
                        //-年
                        cal.add(Calendar.YEAR, 1);
                    }
                    userVip.setIsVip(2);
                    //更新会员的开通时间
                    userVip.setCreateTime(sdf.format(new Date()));
                    //更新会员的到期时间
                    userVip.setEndTime(sdf.format(cal.getTime()));
                    //更新会员信息
                    userVipService.updateById(userVip);
                    return Result.success().put("data", "到期会员续费成功！");
                }
            } else {
                //不是会员开通会员
                //创建会员对象
                userVip = new UserVip();
                //设置开通的用户id
                userVip.setUserId(orders.getUserId());
                //设置开通时间
                userVip.setCreateTime(sdf.format(new Date()));
                //日历
                Calendar cal = Calendar.getInstance();
                //判断开通的会员类型
                if (orders.getVipNameType() == 0) {
                    //-月
                    cal.add(Calendar.MONTH, 1);
                } else if (orders.getVipNameType() == 1) {
                    //一季
                    cal.add(Calendar.MONTH, 3);
                } else if (orders.getVipNameType() == 2) {
                    //一年
                    cal.add(Calendar.YEAR, 1);
                }
                userVip.setIsVip(2);
                //设置到期时间
                userVip.setEndTime(sdf.format(cal.getTime()));
                //注册会员信息
                userVipService.save(userVip);
                return Result.success().put("data", "到期会员续费成功！");
            }
        } else if (orders.getOrdersType() == 3) {//余额充值
            UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            if (com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(userMoney)){
                //余额充值
                userMoney.setMoney(userMoney.getMoney().add(orders.getPayMoney()));
                userMoneyService.updateById(userMoney);
            }else {
                UserMoney money = new UserMoney();
                money.setUserId(orders.getUserId());
                money.setMoney(orders.getPayMoney());
                userMoneyService.save(money);
            }
            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
            userMoneyDetails.setUserId(orders.getUserId());
            userMoneyDetails.setMoney(orders.getPayMoney());
            userMoneyDetails.setTitle("充值成功，订单号："+orders.getOrdersNo());
            userMoneyDetails.setType(1);
            userMoneyDetails.setState(2);
            userMoneyDetails.setMoney(orders.getPayMoney());
            userMoneyDetails.setContent("增加金额："+orders.getPayMoney());
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            userMoneyDetails.setCreateTime(format);
            userMoneyDetails.setPayType(4);
            userMoneyDetailsService.save(userMoneyDetails);
        } else if (orders.getOrdersType() == 4) {//购买剧点
            PayClassify payClassify = payClassifyDao.selectById(orders.getPayClassifyId());
            UserDramaPoint userDramaPoint = userDramaPointDao.selectOne(new QueryWrapper<UserDramaPoint>().eq("user_id", orders.getUserId()));
            if (ObjectUtils.isNotEmpty(userDramaPoint)){
                userDramaPoint.setBalance(userDramaPoint.getBalance().add(new BigDecimal(payClassify.getCoin())).add(new BigDecimal(payClassify.getGiveCoin())));
                userDramaPointDao.updateById(userDramaPoint);
                UserDramaDetails userDramaDetails = new UserDramaDetails();
                userDramaDetails.setUserId(orders.getUserId().intValue());
                userDramaDetails.setOrdersId(orders.getOrdersId().intValue());
                userDramaDetails.setTitle("购买剧点成功，订单号："+orders.getOrdersNo());
                userDramaDetails.setType(2);
                userDramaDetails.setAmount(new BigDecimal(payClassify.getCoin()).add(new BigDecimal(payClassify.getGiveCoin())));
                userDramaDetails.setContent("增加剧点："+new BigDecimal(payClassify.getCoin()).add(new BigDecimal(payClassify.getGiveCoin()))+"点");
            }
        }
        return Result.success("订单处理完成！");
    }

    /**
     * 生成商品订单信息
     *
     * @param courseId
     * @param userId
     * @return
     */
    @Override
    public Result insertCourseOrders(Long courseId, Long courseDetailsId, Long userId) {
        log.info("生成商品订单信息接口入参为：{},{}", courseId, userId);
        reentrantReadWriteLock.writeLock().lock();
        try {
            /*CourseUser courseUser1 = courseUserDao.selectCourseUser(courseId, userId);
            if(courseUser1!=null){
                return Result.error("您已经购买过了，请不要重复点击！");
            }*/
            //返回的类型
            Map<String, Object> result = new HashMap<>();
            //查询会员信息
            UserVip userVip = userVipService.selectUserVipByUserId(userId);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //订单模板对象
            Orders orders = new Orders();
            if (courseId != null) {
                //根据短剧id去查询短剧相关信息 来填充订单模板
                QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("is_delete", 0);
                //短剧必须是未删除的
                queryWrapper.eq("course_id", courseId);
                Course course = courseDao.selectOne(queryWrapper);
                if (course == null) {
                    return Result.error("系统繁忙，请刷新后重试！");
                }
                //设置订单编号
                orders.setOrdersNo(AliPayOrderUtil.createOrderId());
                //设置用户id
                orders.setUserId(userId);
                //设置短剧id
                orders.setCourseId(courseId);
                orders.setCourseDetailsId(courseDetailsId);
                if (courseDetailsId != null) {//购买单集
                    CourseDetails courseDetails = courseDetailsService.getById(courseDetailsId);
                    orders.setPayMoney(courseDetails.getPrice());
                } else {//购买整剧
                    orders.setPayMoney(course.getPrice());
                }
                //设置支付状态
                orders.setStatus(0);
                //设置订单创建时间
                orders.setCreateTime(df.format(new Date()));
                //设置订单种类
                orders.setOrdersType(1);

                //不是会员或会员过期直接生成订单直接生成订单
                int count = baseMapper.insertOrders(orders);
                result.put("flag", 2);
                result.put("orders", orders);
                if (count > 0) {
                    return Result.success("生成订单成功！").put("data", result);
                } else {
                    return Result.error("生成订单失败！");
                }
            } else {
                return Result.error("短剧的id不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成商品订单错误！！！" + e.getMessage());
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    /**
     * 生成会员订单
     *
     * @param vipDetailsId 会员详情id
     * @param userId
     * @return
     */
    @Override
    public Result insertVipOrders(Long vipDetailsId,String purchaseId, Long userId) {
        VipDetails vipDetails = vipDetailsService.getById(vipDetailsId);
        //创建订单返回对象
        Orders orders = new Orders();
        //设置订单编号
        orders.setOrdersNo(AliPayOrderUtil.createOrderId());
        //设置支付金额
        orders.setPayMoney(vipDetails.getMoney());
        //设置订单类型
        orders.setOrdersType(OrdersConstants.ORDERS_TYPE_VIP);
        //设置要开通的会员类型
        orders.setVipNameType(vipDetails.getVipNameType());
        //设置支付状态
        orders.setStatus(OrdersConstants.ORDERS_STATUS_WAIT);
        //设置用户id
        orders.setUserId(userId);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置创建时间
        orders.setCreateTime(df.format(new Date()));
        //设置内购id
        orders.setPurchaseId(purchaseId);
        //插入到订单表中
        baseMapper.insertOrders(orders);
//        ===============苹果支付需要信息========================
        OrdesVo ordesVo = new OrdesVo();
        ordesVo.setOrderId(orders.getOrdersId().toString());
        ordesVo.setMerchantId("merchant.app.QiWang.com");
        ordesVo.setProductType("consumable");
        ordesVo.setQuantity(1);
        ProductVo productVo = new ProductVo();
        productVo.setDescription("会员购买");
        productVo.setName("会员");
        BigDecimal payMoney = orders.getPayMoney();
        productVo.setPrice(payMoney.multiply(new BigDecimal(100)));
        ordesVo.setProductVo(productVo);
//        ============================
        return Result.success().put("data", ordesVo);
    }

    /**
     *  余额支付：记录邀请和计算邀请人收益(不单单是会员有佣金，用户消费就有佣金)，
     *  记录用户钱包明细，记录邀请明细，记录邀请人钱包明细，
     *  该方法是用户购买商品和会员的支付方法，短剧添加到我的短剧里，会员则根据情况更新到期时间等
     * @param ordersId 订单id
     * @return
     */
    @Override
    public Result payMoney(Long ordersId) {
        reentrantReadWriteLock.writeLock().lock();
        try{
            Orders orders = baseMapper.selectById(ordersId);
            System.out.println("================>orders"+orders);
            if (orders == null || !orders.getStatus().equals(0)) {
                return Result.error("订单错误，请刷新后重试！");
            }
            //根据用户id查询用户钱包
            UserMoney userMoney = userMoneyService.selectUserMoneyByUserId(orders.getUserId());
            //根据用户id查询邀请收益钱包
            InviteMoney inviteMoney = inviteMoneyDao.selectInviteMoneyByUserId(orders.getUserId());
            if (userMoney.getMoney().doubleValue() >= orders.getPayMoney().doubleValue()) {//判断余额是否足够
                UserEntity userEntity = userService.selectUserById(orders.getUserId());
                //扣减用户钱包余额
                userMoneyService.updateMoney(2, orders.getUserId(), orders.getPayMoney().doubleValue());
                //钱包详情记录
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setMoney(orders.getPayMoney());
                userMoneyDetails.setUserId(orders.getUserId());
                userMoneyDetails.setContent("零钱支付订单");
                userMoneyDetails.setTitle("下单成功，订单号：" + orders.getOrdersNo());
                userMoneyDetails.setType(2);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
                //修改订单的状态
                orders.setPayWay(6);
                orders.setStatus(1);
                baseMapper.updateById(orders);
                //通过邀请码查询邀请人
                UserEntity byUser = userService.queryByInvitationCode(userEntity.getInviterCode());
                //记录邀请和计算邀请收益(不单单是会员有佣金，用户消费就有佣金)
                inviteService.updateInvite(byUser, DateUtils.format(new Date()), userEntity.getUserId(), orders.getPayMoney());
                //默认订单为短剧和会员，短剧添加到我的短剧里，会员则根据情况更新到期时间等
                insertOrders(orders);
                return Result.success();
            } else {
                //判断用户邀请收益余额加上用户余额是否足够支付
                BigDecimal add = BigDecimal.valueOf(inviteMoney.getMoney()).add(userMoney.getMoney());
                if (add.doubleValue() < orders.getPayMoney().doubleValue()) {
                    return Result.error("账户不足，请充值！");
                }
                UserEntity userEntity = userService.selectUserById(orders.getUserId());
                //2为扣减用户钱包费用
                userMoneyService.updateMoney(2, orders.getUserId(), userMoney.getMoney().doubleValue());
                UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                userMoneyDetails.setMoney(orders.getPayMoney());
                userMoneyDetails.setUserId(orders.getUserId());
                userMoneyDetails.setContent("零钱支付订单");
                userMoneyDetails.setTitle("下单成功，订单号：" + orders.getOrdersNo());
                userMoneyDetails.setType(2);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                userMoneyDetailsService.save(userMoneyDetails);
                BigDecimal subtract = orders.getPayMoney().subtract(userMoney.getMoney());
                //扣减用户邀请收益余额
                inviteMoneyDao.updateInviteMoneySumSub(subtract.doubleValue(), orders.getUserId());
                //记录支付方式和修改订单状态
                orders.setPayWay(6);
                orders.setStatus(1);
                baseMapper.updateById(orders);
                //通过邀请人邀请码查询邀请人
                UserEntity byUser = userService.queryByInvitationCode(userEntity.getInviterCode());
                //记录邀请和计算邀请收益(不单单是会员有佣金，用户消费就有佣金)
                inviteService.updateInvite(byUser, DateUtils.format(new Date()), userEntity.getUserId(), orders.getPayMoney());
                //默认订单为短剧和会员，短剧添加到我的短剧里，会员则根据情况更新到期时间等
                insertOrders(orders);
                return Result.success();
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("零钱支付订单异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.success();
    }

    /**
     *支付宝退款
     * @param ordersId 订单id
     * @param refundContent 退款原因
     */
    @Override
    public Result refundOrder(Long ordersId, String refundContent) {
        Orders bean = baseMapper.selectById(ordersId);
        if (!bean.getStatus().equals(1)) {
            return Result.error("订单未支付或已退款！");
        }
        bean.setRefundContent(refundContent);
        if (bean.getPayWay() == 1 || bean.getPayWay() == 2 || bean.getPayWay() == 3) {
            boolean refund = wxService.refund(bean);
            if (!refund) {
                return Result.error("退款失败！");
            }
        } else if(bean.getPayWay()==4){
            String code = aliPayController.alipayRefund(bean);
            if (StringUtils.isNotBlank(code)) {
                JSONObject jsonObject = JSON.parseObject(code);
                JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                String code1 = alipay_trade_refund_response.getString("code");
                if (!"10000".equals(code1)) {
                    return Result.error("退款失败！");
                }
            } else {
                return Result.error("退款失败！");
            }
        }else{
            userMoneyService.updateMoney(1,bean.getUserId(),bean.getPayMoney().doubleValue());
            UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
            userMoneyDetails.setMoney(bean.getPayMoney());
            userMoneyDetails.setUserId(bean.getUserId());
            userMoneyDetails.setContent("订单:"+bean.getOrdersNo());
            userMoneyDetails.setTitle("订单退款："+bean.getPayMoney());
            userMoneyDetails.setType(1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
            userMoneyDetailsService.save(userMoneyDetails);
        }
        bean.setStatus(2);
        baseMapper.updateById(bean);
        if (bean.getOrdersType() == 1) {
            CourseUser courseUser = courseUserDao.selectOne(new QueryWrapper<CourseUser>().eq("order_id", bean.getOrdersId()));
            if (courseUser != null) {
                courseUserDao.deleteById(courseUser.getCourseUserId());
            }
        } else {
            UserVip userVip = userVipService.selectUserVipByUserId(bean.getUserId());
            if (userVip != null) {
                userVipService.removeById(userVip.getVipId());
            }
            courseUserDao.deleteCourseUserByVipUser(bean.getUserId());
        }
        return Result.success("退款成功！");
    }

    @Override
    public Result selectOrders(Integer page, Integer limit, String ordersNo, Integer status, Long userId) {
        Page<Orders> pages = new Page<>(page, limit);
        return Result.success().put("data", new PageUtils(baseMapper.selectOrdersByOrdersNo(pages, ordersNo, status, userId)));
    }

    @Override
    public Result selectOrderByUserId(Integer page, Integer limit, Long userId) {
        IPage<Orders> orderPage = new Page<>(page, limit);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("orders_type", 1);
        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("create_time");
        IPage<Orders> iPage = baseMapper.selectPage(orderPage, queryWrapper);
        List<Orders> bean = iPage.getRecords();
        if (bean != null && bean.size() > 0) {
            for (int i = 0; bean.size() > i; i++) {
                bean.get(i).setCourse(courseDao.selectById(bean.get(i).getCourseId()));
            }
        }
        return Result.success().put("data", iPage);
    }

    @Override
    public Result deleteOrders(String ids) {
        String[] split = ids.split(",");
        baseMapper.deleteOrders(split);
        return Result.success();
    }


    @Override
    public Orders selectOrderById(Long orderId) {
        return baseMapper.selectById(orderId);
    }

    @Override
    public Orders selectOrderByOrdersNo(String ordersNo) {
        return baseMapper.selectOne(new QueryWrapper<Orders>().eq("orders_no", ordersNo));
    }

    @Override
    public Double statisticsIncomeMoney(String time, Integer flag, Integer ordersType) {
        return baseMapper.statisticsIncomeMoney(time, flag, ordersType);
    }

    @Override
    public Result selectOrdersMoneyList(Integer page, Integer limit, Integer flag, String time) {
        return Result.success().put("data", baseMapper.selectOrdersMoneyList(new Page<>(page, limit), flag, time));
    }


    @Override
    public Integer selectOrdersCount(Integer status, Integer ordersType, Integer flag, String time) {
        return baseMapper.selectOrdersCount(status, ordersType, flag, time);
    }

    @Override
    public Double selectOrdersMoney(Integer status, Integer ordersType, Integer flag, String time) {
        return baseMapper.selectOrdersMoney(status, ordersType, flag, time);
    }

    /**
     * 消费记录
     * @param page 页数
     * @param limit 条数
     * @param userId 用户id
     * @return 消费记录信息
     */
    @Override
    public Result consumeRecords(Integer page, Integer limit, Long userId) {
        IPage<Orders> orderPage = new Page<>(page, limit);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId);
        queryWrapper.eq(Orders::getStatus, 1);
        IPage<Orders> ordersIPage = baseMapper.selectPage(orderPage, queryWrapper);
        if (ObjectUtils.isNotEmpty(ordersIPage)){
            for (Orders record : ordersIPage.getRecords()) {
                record.setCourse(courseDao.selectById(record.getCourseDetailsId()));
            }
        }
        return Result.success().put("date",ordersIPage);
    }

    /**
     * 购买剧点
     * @param classifyId 剧点id
     * @param userId 用户id
     * @return
     */
    @Override
    public Result topUpPayClassify(Integer classifyId, Long userId) {
        log.info("===========  topUpPayClassify  "+"购买剧点，classifyId:{},userId:{}",classifyId,userId+"===========");
        reentrantReadWriteLock.writeLock().lock();
        PayClassify payClassify = payClassifyDao.selectById(classifyId);
        if (ObjectUtils.isEmpty(payClassify)){
            return Result.error().put("msg","剧点分类不存在");
        }
        Orders orders = new Orders();
        try {
            orders.setUserId(userId);
            orders.setOrdersNo(AliPayOrderUtil.createOrderId());
            orders.setPayMoney(payClassify.getPrice());
            orders.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            orders.setStatus(0);
            orders.setOrdersType(4);
            orders.setPayClassifyId(classifyId);
            baseMapper.insert(orders);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.success().put("data",orders);
    }

    @Override
    public Result selDramaPoint(Integer page,Integer limit,Long userId) {
        Page<UserDramaDetails> dramaPage = new Page<>(ObjectUtils.isEmpty(page)?1:page, ObjectUtils.isEmpty(limit)?5:limit);
        LambdaQueryWrapper<UserDramaDetails> userDramaDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userDramaDetailsLambdaQueryWrapper.eq(UserDramaDetails::getUserId, userId);
        IPage<UserDramaDetails> userDramaDetailsIPage = userDramaDetailsDao.selectPage(dramaPage, userDramaDetailsLambdaQueryWrapper);
        userDramaDetailsIPage.getRecords().stream().map(userDramaDetails -> {
            //返回购买剧集信息
            if (userDramaDetails.getType()==2){
                //根据订单id查剧或剧集信息
                LambdaQueryWrapper<CourseUser> courseUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                courseUserLambdaQueryWrapper.eq(CourseUser::getOrderId, userDramaDetails.getOrdersId());
                CourseUser courseUser = courseUserDao.selectOne(courseUserLambdaQueryWrapper);
                if (courseUser.getClassify()==1)userDramaDetails.setCourseName(courseDao.selectById(courseUser.getCourseId()).getTitle()+"·整剧解锁");
                if (courseUser.getClassify()==2)userDramaDetails.setCourseName(courseDetailsDao.selectById(courseUser.getCourseDetailsId()).getCourseDetailsName());
            }
            return userDramaDetails;
        }).collect(Collectors.toList());
        return Result.success().put("data",userDramaDetailsIPage);
    }

    @Autowired
    private OrdersService ordersService;
    /**
     * 剧点支付
     * @param
     * @return
     */
    @Override
    @Transactional
    public Result dramaPointPay(Long userId, DramaPointPayDto dramaPointPayDto) {
        CourseDetails courseDetails = courseDetailsService.getById(dramaPointPayDto.getCourseDetails());
        if (ObjectUtils.isNotEmpty(courseDetails)&&courseDetails.getIsPrice()==1){
            Orders orders1 = new Orders();
            orders1.setUserId(userId);
            orders1.setPayMoney(courseDetails.getPrice().divide(new BigDecimal(10),2,RoundingMode.HALF_UP));
            orders1.setOrdersNo(AliPayOrderUtil.createOrderId());
            orders1.setPayWay(OrdersConstants.ORDERS_PAY_WAY_JUPOINT);
            orders1.setStatus(OrdersConstants.ORDERS_STATUS_WAIT);
            orders1.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            orders1.setOrdersType(1);
            orders1.setCourseId(dramaPointPayDto.getCourseId().longValue());
            if (ObjectUtils.isNotEmpty(dramaPointPayDto.getCourseDetails())){
                orders1.setCourseDetailsId(dramaPointPayDto.getCourseDetails().longValue());
            }
            ordersDao.insert(orders1);
            LambdaQueryWrapper<UserDramaPoint> userDramaPointLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userDramaPointLambdaQueryWrapper.eq(UserDramaPoint::getUserId, orders1.getUserId());
            UserDramaPoint userDramaPoint = userDramaPointDao.selectOne(userDramaPointLambdaQueryWrapper);
            if (ObjectUtils.isNotEmpty(userDramaPoint)&&userDramaPoint.getBalance().doubleValue()>= orders1.getPayMoney().doubleValue()){
                //扣除剧点 todo 剧点金额为短剧价格*10
                userDramaPoint.setBalance(userDramaPoint.getBalance().subtract(orders1.getPayMoney()));
                userDramaPointDao.updateById(userDramaPoint);
                System.out.println("用户剧点购买后的余额："+userDramaPoint.getBalance());
                //修改支付状态
                orders1.setStatus(1);
                baseMapper.updateById(orders1);
                //记录购买的剧,购买的整部剧
                ordersService.insertOrders(orders1);

                //记录一条剧点详情
                UserDramaDetails userDramaDetails = new UserDramaDetails();
                userDramaDetails.setAmount(orders1.getPayMoney());
                userDramaDetails.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                userDramaDetails.setUserId(orders1.getUserId().intValue());
                userDramaDetails.setType(2);
                userDramaDetails.setContent("减少剧点："+orders1.getPayMoney()+"点");
                if (ObjectUtils.isNotEmpty(orders1.getCourseDetailsId())){
                    userDramaDetails.setTitle("剧集购买成功,订单号："+orders1.getOrdersNo());
                }else {
                    userDramaDetails.setTitle("整剧购买成功,订单号："+orders1.getOrdersNo());
                }
                userDramaDetails.setOrdersId(orders1.getOrdersId().intValue());
                userDramaDetailsDao.insert(userDramaDetails);
                //todo 购买次数+1
            }else if (ObjectUtils.isNotEmpty(userDramaPoint)&&userDramaPoint.getBalance().doubleValue()< orders1.getPayMoney().doubleValue()){
                return Result.error("剧点余额不足");
            }
        }

        return Result.success();
    }

    @Override
    public Result selectDramBalance(Long userId) {
        LambdaQueryWrapper<UserDramaPoint> userDramaPointLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userDramaPointLambdaQueryWrapper.eq(UserDramaPoint::getUserId, userId);
        UserDramaPoint userDramaPoint = userDramaPointDao.selectOne(userDramaPointLambdaQueryWrapper);
        if (ObjectUtils.isEmpty(userDramaPoint)){
            userDramaPoint = new UserDramaPoint();
            userDramaPoint.setUserId(userId.intValue());
            userDramaPoint.setBalance(BigDecimal.ZERO);
            userDramaPointDao.insert(userDramaPoint);
        }
        return Result.success().put("data",userDramaPoint.getBalance());
    }

    /**
     * 充值余额记录查询
     * @param userId
     * @return
     */
    @Override
    public Result rechargeBalance(Long userId,Integer page,Integer limit) {
        Page<PayDetails> Ipage = new Page<>(ObjectUtils.isEmpty(page) ? 1 : page, ObjectUtils.isEmpty(limit) ? 10 : limit);
        LambdaQueryWrapper<PayDetails> payDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        payDetailsLambdaQueryWrapper.eq(PayDetails::getUserId, userId);
        payDetailsLambdaQueryWrapper.eq(PayDetails::getState,1);
        IPage<PayDetails> selectPage = payDetailsDao.selectPage(Ipage, payDetailsLambdaQueryWrapper);
        return Result.success().put("data",selectPage);
    }


}
